package com.ldk.framework.service.impl;

import java.util.Date;
import java.util.List;

import com.ldk.base.framework.util.ConvertUtil;
import com.ldk.framework.entity.*;
import com.ldk.framework.service.ICouponService;
import com.ldk.framework.service.IDictdataService;
import com.ldk.framework.service.IDriverService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ldk.base.framework.dao.IBaseDAO;
import com.ldk.base.framework.service.impl.BaseService;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.service.IUserService;
import com.ldk.framework.dao.IRechargeRecordDAO;
import com.ldk.framework.dao.IUserDAO;
import com.ldk.framework.enums.PlatformUserType;
import com.ldk.framework.enums.RechargeFrom;

/**
* UserService接口实现类
* @author xiangwl
*/
@Service
public class UserService extends BaseService<User> implements IUserService {

	@Autowired
	private IUserDAO userDAO;
	@Autowired
	private IRechargeRecordDAO rechargeRecordDAO;
	@Autowired
	protected IDictdataService dictdataService;
	@Autowired
	protected ICouponService couponService;
	@Autowired
	protected IDriverService driverService;

	@Override
	protected IBaseDAO<User> getBaseDao() {
     	return this.userDAO;
	}
	
	@Override
	public Boolean existByOpenId(String dbKey, String openId) {
		try {
			User query=new User();
			query.setOpenId(openId);
			query.setEnabled(true);
			long count = userDAO.selectCount(dbKey, query);
			
			return count > 0;
			
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return false;
	}

	@Override
	public User getUserByOpenId(String dbKey, String openId) {
		try {
			User query=new User();
			query.setOpenId(openId);
			query.setEnabled(true);
			return userDAO.selectOne(dbKey, query);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return null;
	}
	
	@Override
	public User getUserByPhone(String dbKey, String phoneNo) {
		try {
			User query=new User();
			query.setPhoneNo(phoneNo);
			query.setEnabled(true);
			return userDAO.selectOne(dbKey, query);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return null;
	}
	
	@Override
	public LinkUser getLinkUser(String dbKey, String openId) {
		try {
			return userDAO.getLinkUser(dbKey, openId);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return null;
	}

	@Override
	@Transactional
	public Boolean recharge(String dbKey, String userName,
			Double rechargeMoney, int rechargeType, int rechargeFrom,
			String operator) throws Exception {
		User query = new User();
		query.setPhoneNo(userName);
		query.setEnabled(true);


		User user = userDAO.selectOne(dbKey, query);
		if(user == null) return false;

		Double beforeBalance = user.getBalance() == null ? 0 : user.getBalance();
		Double afterBalance = beforeBalance + rechargeMoney.doubleValue();
		User entity = new User();
		entity.setUserId(user.getUserId());
		entity.setBalance(afterBalance);
		int row = userDAO.updateByKey(dbKey, entity);
		if(row > 0){
			RechargeRecord record = new RechargeRecord();
			record.setRecordNo(SystemUtil.generateRandomNo(""));
			record.setPhoneNo(userName);
			record.setUserType(PlatformUserType.CLIENT_USER.getValue());
			record.setRechargeMoney(rechargeMoney);
			record.setBeforeBalance(beforeBalance);
			record.setAfterBalance(afterBalance);
			record.setOperator(operator);
			record.setRechargeType(rechargeType);
			record.setRechargeTime(SystemUtil.getAllSeconds());
			if(rechargeFrom < 1)
				rechargeFrom = RechargeFrom.FROM_ADMIN.getValue();
			record.setRechargeFrom(rechargeFrom);

			row = rechargeRecordDAO.insert(dbKey,  record);
		}
		
		return row > 0;
	}

	@Override
	public boolean balancePay(String dbKey, String userName, double balance) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Boolean refund(String dbKey, String userName, Double refundMoney,
			int rechargeType, int rechargeFrom, String operator) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Boolean updateNickName(String dbKey, long userId, String nickName) {
		User entity = new User();
		entity.setUserId(userId);
		entity.setNickName(nickName);
		int row = updateByKey(dbKey, entity);
		return row > 0;
	}

	@Override
	public Boolean updateRemark(String dbKey, long userId, String remark) {
		User entity = new User();
		entity.setUserId(userId);
		entity.setRemark(remark);
		int row = updateByKey(dbKey, entity);
		return row > 0;
	}

	@Override
	public Boolean updatePicture(String dbKey, long userId, String picture) {
		User entity = new User();
		entity.setUserId(userId);
		entity.setPicture(picture);
		int row = updateByKey(dbKey, entity);
		return row > 0;
	}

	@Override
	public Boolean updateLocation(String dbKey, long userId, double lon, double lat) {
		User entity = new User();
		entity.setUserId(userId);
		entity.setLat(lat);
		entity.setLon(lon);
		int row = updateByKey(dbKey, entity);
		return row > 0;
	}

	@Override
	public List<User> searchByDistance(String dbKey, User query, double lon,
			double lat, double distance) {
		if(lon <= 0 || lat <= 0)
			return null;
		if(distance < 1){
			distance = 30 * 1000;
		}
		return userDAO.searchByDistance(dbKey, query, lon, lat, distance);
	}

	/**
	 * 生成8位固定ID号
	 */
	public long generateUCommonId() {
		long uCommonId = this.generateID(8);
		while (true) {
			User query = new User();
			query.setuCommonId(uCommonId);
			long count = this.selectCount("", query);
			if(count > 0){
				uCommonId = this.generateID(8);
			}else{
				break;
			}
		}
		return uCommonId;
	}

	@Override
	public Boolean existUCommonId(long uCommonId) {
		User query = new User();
		query.setuCommonId(uCommonId);
		long count = selectCount("", query);

		if(count > 0){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public void insertCoupon(User user) {
		long rCommonId = user.getrCommonId();
		String commonId = ConvertUtil.parseString(rCommonId);
		Date cur_date = new Date();
		long createTime = SystemUtil.getAllSeconds(cur_date);

		Dictdata query3 = new Dictdata();
		query3.setDataId(11);  //优惠券过期时间(单位:天)
		Dictdata data3 = dictdataService.selectByKey("",query3);


		if(commonId.length() ==6) {
			//A=>B
			//A
			Dictdata query = new Dictdata();
			query.setDataId(13);  //司机返现金卷(元)
			Dictdata data1 = dictdataService.selectByKey("",query);

			//B
			Dictdata query2 = new Dictdata();
			query2.setDataId(14);  //乘客返优惠卷(元)
			Dictdata data2 = dictdataService.selectByKey("",query2);

			//1、奖励推荐人
			// 推荐人信息
			Driver query_driver = new Driver();
			//query_driver.setdCommonId(user.getrCommonId());
			Driver driver2 = driverService.selectOne("", query_driver);

			//奖励现金券
			Coupon entity = new Coupon();
			entity.setUserId(driver2.getDriverId());
			entity.setCouponType(1);  //现金券
			entity.setAmount(ConvertUtil.parseDouble(data1.getDataValue()));
			entity.setCreateTime(createTime);
			entity.setStatus(0);
			int row = couponService.insert("", entity);

			//修改现金券余额
			Driver entity_driver= new Driver();
			entity_driver.setDriverId(driver2.getDriverId());
			//entity_driver.setCashCoupon(driver2.getCashCoupon() + ConvertUtil.parseDouble(data1.getDataValue()));  //更新现金卷总额
			int row2 = driverService.updateByKey("", entity_driver);

			//2、奖励被推荐人
			//奖励优惠劵
			Coupon entity2 = new Coupon();
			entity2.setUserId(user.getUserId());
			entity2.setCouponType(0);  //优惠劵
			entity2.setAmount(ConvertUtil.parseDouble(data2.getDataValue()));
			entity2.setCreateTime(createTime);

			//设置过期时间
			long expireTime = SystemUtil.getAddDaysAllSeconds(cur_date,ConvertUtil.parseInt(data3.getDataValue()));
			entity2.setExpireTime(expireTime);

			entity2.setStatus(0);
			int row3 = couponService.insert("", entity2);

			//修改优惠劵
			User entity_user = new User();
			entity_user.setUserId(user.getUserId());
			entity_user.setCoupon(user.getCoupon() + ConvertUtil.parseDouble(data2.getDataValue()));  //更新优惠劵总额
			int row4 = updateByKey("", entity_user);

		} else  if(commonId.length() ==8) {
			Dictdata query = new Dictdata();
			query.setDataId(19);  //推荐人返优惠券(元)
			Dictdata data1 = dictdataService.selectByKey("",query);

			Dictdata query2 = new Dictdata();
			query2.setDataId(20);  //被推荐人返优惠券(元)
			Dictdata data2 = dictdataService.selectByKey("",query2);

			//1、奖励推荐人
			// 推荐人信息
			User query_user = new User();
			query_user.setuCommonId(user.getrCommonId());
			User user2 = selectOne("", query_user);

			//奖励优惠券
			Coupon entity = new Coupon();
			entity.setUserId(user2.getUserId());
			entity.setCouponType(0);  //优惠劵
			entity.setAmount(ConvertUtil.parseDouble(data1.getDataValue()));
			entity.setCreateTime(createTime);

			//设置过期时间
			long expireTime = SystemUtil.getAddDaysAllSeconds(cur_date,ConvertUtil.parseInt(data3.getDataValue()));
			entity.setExpireTime(expireTime);

			entity.setStatus(0);
			int row = couponService.insert("", entity);

			//修改优惠卷总额
			User entity_user= new User();
			entity_user.setUserId(user2.getUserId());
			entity_user.setCoupon(user2.getCoupon() + ConvertUtil.parseDouble(data1.getDataValue()));
			int row2 = updateByKey("", entity_user);

			//2、奖励被推荐人
			//奖励优惠卷
			Coupon entity2 = new Coupon();
			entity2.setUserId(user.getUserId());
			entity2.setCouponType(0);  //优惠卷
			entity2.setAmount(ConvertUtil.parseDouble(data2.getDataValue()));
			entity2.setCreateTime(createTime);

			//设置过期时间
			entity2.setExpireTime(expireTime);

			entity2.setStatus(0);
			int row3 = couponService.insert("", entity2);

			//修改优惠卷余额
			User entity_user2 = new User();
			entity_user2.setUserId(user.getUserId());
			entity_user2.setCoupon(user.getCoupon() + ConvertUtil.parseDouble(data2.getDataValue()));  //更新优惠卷总额
			int row4 = updateByKey("", entity_user2);
		}
	}
}
